// 页面路由
var express = require('express');
var router = express.Router();
// 引入mysql模块 相对路径
var sql = require('../mysql/config');
//　定义全局数据变量
var nav,banner,boutique,free;
var md = require('markdown-it')();
// 自运行函数
(async function(){
  // 请求的公共的数据
  nav = await sql('select * from nav');
  banner = await sql('select * from banner');
  boutique = await sql(`select article_id,thumb,title,intro from article where sort_id = 1`);
  free = await sql(`select article_id,thumb,title,intro from article where sort_id = 2`);
})()

/* GET index page. */
router.get('/',async function(req, res) { 

  // 中间件  --  处理逻辑
  // 方案一
  // var article = await sql(`select sort_id, thumb,title,intro from article`);  // [{}，{}]
  // console.log(article);
  // var boutique = article.filter(item=>{
  //   return item.sort_id === 1;
  // })
  // var free = article.filter(item=>{
  //   return item.sort_id === 2;
  // })

  // console.log("boutique ====> " , boutique);
  // console.log("<====================>====>");
  // console.log("free ====> " , free);

  // 方案二
  // var boutique = await sql(`select thumb,title,intro from article where sort_id = 1`);
  // var free = await sql(`select thumb,title,intro from article where sort_id = 2`);

  // console.log("boutique ====> " , boutique);
  // console.log("<====================>====>");
  // console.log("free ====> " , free);

  var boutiqueIndex = boutique.slice(0,4);
  var freeIndex = free.slice(0,12);
  if (req.session.user) {
    var { id } =  req.session.user;
    var data = await sql(`select nickname,avatar from user where id = ${ id }`);
    var { nickname,avatar } = data[0];
    res.render('index',{title:'首页',nav,banner,nickname,avatar,isUser:false,boutiqueIndex,freeIndex});
  }else{
    res.render('index',{title:'首页',nav,banner,isUser:true,boutiqueIndex,freeIndex});
  }
  
});

/* GET index page. */
router.get('/index', async function(req, res) {
  // 写逻辑 连接数据库 请求数据 传递给页面渲染
  var boutiqueIndex = boutique.slice(0,4);
  var freeIndex = free.slice(0,12);
  if (req.session.user) {
    var { id } =  req.session.user;
    var data = await sql(`select nickname,avatar from user where id = ${ id }`);
    var { nickname,avatar } = data[0];
    res.render('index',{title:'首页',nav,banner,nickname,avatar,isUser:false,boutiqueIndex,freeIndex});
  }else{
    res.render('index',{title:'首页',nav,banner,isUser:true,boutiqueIndex,freeIndex});
  }
});

/* GET boutique page. */
router.get('/boutique', async function(req, res) {
  // 写逻辑 连接数据库 请求数据 传递给页面渲染
  // 获取当前页面的分页按钮数量
  var btnNum = Math.ceil(boutique.length / 8);
  if (req.session.user) {
    var { id } =  req.session.user;
    var data = await sql(`select nickname,avatar from user where id = ${ id }`);
    var { nickname,avatar } = data[0];
    res.render('boutique',{title:'精品',nav,nickname,avatar,isUser:false,boutique,btnNum});
  }else{
    res.send("<script>alert('需要登录之后，才能访问该页面...');location.href='/';</script>")
    //res.redirect('/');
  }
  
});

/* GET free page. */
router.get('/free', async function(req, res) {
  // 获取当前页面的分页按钮数量
  var btnNum = Math.ceil(free.length / 8);

  if (req.session.user) {
    var { id } =  req.session.user;
    var data = await sql(`select nickname,avatar from user where id = ${ id }`);
    var { nickname,avatar } = data[0];
    res.render('free',{title:'免费',nav,nickname,avatar,isUser:false,free,btnNum});    
  }else{
    res.render('free',{title:'免费',nav,isUser:true,free,btnNum});
  }

});

/* GET detail page. */
router.get('/detail', async function(req, res) {
  // query 传参  /detail?id=1&name="zhangsan"
  // console.log("文章详情===》",req.query);
  // 查找对应的文章内容
  let article_id = Number(req.query.id);
 
  let article = await sql(`select * from article where article_id = ${article_id} `);
  let hits = article[0].hits || 0;
  hits++;
  await sql(`update article set hits = ? where article_id = ${article_id}`,[hits]);
  article = await sql(`select * from article where article_id = ${article_id} `);
  // console.log("文章内容===》",article);
  article = article[0]
  // params 传参 /detail/1/zhangsan   接收的形式 /detail/:id/:name
  // console.log("文章详情===》",req.params);
  article.content = md.render(article.content);

  if (req.session.user) {
    var { id } =  req.session.user;
    var data = await sql(`select nickname,avatar from user where id = ${ id }`);
    var { nickname,avatar } = data[0];
    let thumbsUp = await sql(`select on_off from thumbs_up where nickname = ? and article_id = ?`,[nickname,article_id]);
      let onOff
      if (thumbsUp.length !== 0) {
        onOff = thumbsUp[0].on_off;
      }
    res.render('detail',{title:'详情',nav, nickname, avatar, isUser:false,article });
  }else{
    res.render('detail',{ title:'详情',nav, isUser:true,article });
  } 
});

//article
router.get('/article', async function(req, res) {
  if(req.session.user){
    var { id,username } =  req.session.user;
    // console.log(username,"++++++++++++++++++");
    var data = await sql(`select nickname,avatar from user where id = ${ id }`);
    var { nickname,avatar } = data[0];
    res.render('article',{title:'用户设置',nav, nickname, avatar, isUser:false ,username });
  }else{
    res.render('article',{title:'用户设置',nav, isUser:true});
  }
});

/* GET user page. */
router.get('/user', async function(req, res) {
  if(req.session.user){
    var { id,username } =  req.session.user;
    // console.log(username,"++++++++++++++++++");
    var data = await sql(`select nickname,avatar from user where id = ${ id }`);
    var { nickname,avatar } = data[0];
    res.render('user',{title:'用户设置',nav, nickname, avatar, isUser:false ,username });
  }else{
    res.render('user',{title:'用户设置',nav, isUser:true});
  }
});



/* GET search page. */
router.get('/search', async function(req, res) {
  // 搜索的关键字
  var s = req.query.s;
  console.log('search=====>',s);
  var search = await sql(`select * from article where content like "%${s}%"`);

  console.log(search);

  // 获取当前页面的分页按钮数量
  var btnNum = Math.ceil(search.length / 8);

  if (req.session.user) {
    var { id } =  req.session.user;
    var data = await sql(`select nickname,avatar from user where id = ${ id }`);
    var { nickname,avatar } = data[0];
    res.render('search',{title:'搜索',nav,nickname,avatar,isUser:false,search,btnNum });    
  }else{
    res.render('search',{title:'搜索',nav,isUser:true,search,btnNum });
  }

});


// 暴露路由
module.exports = router;
